import { h } from 'vue'
import { ElUpload, ElIcon, ElMessage, ElImage, ElTag, ElInput } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

/**
 * 链接表单字段配置
 * 根据类型（type）动态显示不同的字段
 * type: 0-个人作品, 1-优秀站点, 2-友情链接
 */
export const formConfig = [
  // ============ 通用字段（图标/封面图、名称、简介、类型） ============
  // 图标/封面图 - 根据类型动态显示
  {
    field: 'icon',
    label: '图标/封面图',
    component: 'Upload',
    render: (form) => {
      // 个人作品显示封面图
      if (form.type === '0') {
        return h('div', { class: 'cover-upload' }, [
          h(
            ElUpload,
            {
              class: 'cover-uploader',
              action: '/commonApi/upload',
              'show-file-list': false,
              'auto-upload': true,
              accept: 'image/jpeg,image/png,image/jpg,image/webp',
              data: {
                filePath: 'links/cover',
              },
              'before-upload': (file) => {
                const isImage = /^image\/(jpeg|png|jpg|webp)$/.test(file.type)
                const isLt5M = file.size / 1024 / 1024 < 5

                if (!isImage) {
                  ElMessage.error('只能上传图片格式文件！')
                  return false
                }
                if (!isLt5M) {
                  ElMessage.error('图片大小不能超过 5MB！')
                  return false
                }
                return true
              },
              'on-success': (res) => {
                form.coverImage = res.data
              },
            },
            () => [
              form.coverImage
                ? h(ElImage, {
                    src: form.coverImage,
                    class: 'cover-image',
                    previewTeleported: true,
                    fit: 'cover',
                    previewSrcList: [form.coverImage],
                    initialIndex: 0,
                    hideOnClickModal: true,
                    style: {
                      width: '200px',
                      height: '120px',
                      borderRadius: '8px',
                      cursor: 'pointer',
                    },
                  })
                : h('div', { class: 'upload-placeholder cover-placeholder' }, [
                    h(ElIcon, { class: 'upload-icon' }, () => h(Plus)),
                    h('span', '点击上传封面图'),
                  ]),
            ],
          ),
          h(
            'div',
            { class: 'el-upload__tip' },
            '建议尺寸: 800x480px, 支持jpg/png/webp格式，且不超过5MB',
          ),
        ])
      }
      // 优秀站点和友情链接显示图标
      return h('div', { class: 'icon-upload' }, [
        h(
          ElUpload,
          {
            class: 'icon-uploader',
            action: '/commonApi/upload',
            'show-file-list': false,
            'auto-upload': true,
            accept: 'image/jpeg,image/png,image/jpg,image/webp,image/svg+xml',
            data: {
              filePath: 'links/icon',
            },
            'before-upload': (file) => {
              const isImage = /^image\/(jpeg|png|jpg|webp|svg\+xml)$/.test(file.type)
              const isLt2M = file.size / 1024 / 1024 < 2

              if (!isImage) {
                ElMessage.error('只能上传图片格式文件！')
                return false
              }
              if (!isLt2M) {
                ElMessage.error('图片大小不能超过 2MB！')
                return false
              }
              return true
            },
            'on-success': (res) => {
              form.icon = res.data
            },
          },
          () => [
            form.icon
              ? h(ElImage, {
                  src: form.icon,
                  class: 'icon',
                  previewTeleported: true,
                  fit: 'cover',
                  previewSrcList: [form.icon],
                  initialIndex: 0,
                  hideOnClickModal: true,
                  style: {
                    width: '80px',
                    height: '80px',
                    borderRadius: '8px',
                  },
                })
              : h('div', { class: 'upload-placeholder' }, [
                  h(ElIcon, { class: 'upload-icon' }, () => h(Plus)),
                  h('span', '点击上传图标'),
                ]),
          ],
        ),
        h(
          'div',
          { class: 'el-upload__tip' },
          '建议尺寸: 80x80px, 支持jpg/png/svg/webp格式，且不超过2MB',
        ),
      ])
    },
  },

  // 名称 - 通用字段，根据类型动态显示placeholder
  {
    field: 'title',
    label: '名称',
    component: 'Input',
    placeholder: '请输入名称',
    rules: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    render: (form) => {
      const placeholderMap = {
        0: '请输入作品名称',
        1: '请输入站点名称',
        2: '请输入友链名称',
      }
      return h(ElInput, {
        modelValue: form.title,
        'onUpdate:modelValue': (val) => {
          form.title = val
        },
        placeholder: placeholderMap[form.type] || '请输入名称',
      })
    },
  },

  // 简介 - 通用字段
  {
    field: 'description',
    label: '简介',
    component: 'Input',
    placeholder: '请输入简介',
    props: {
      type: 'textarea',
      rows: 3,
      maxlength: 200,
      showWordLimit: true,
    },
    rules: [{ max: 200, message: '简介不能超过200个字符', trigger: 'blur' }],
  },

  // 类型 - 通用字段
  {
    field: 'type',
    label: '类型',
    component: 'Radio',
    defaultValue: '0',
    rules: [{ required: true, message: '请选择类型', trigger: 'change' }],
    options: [
      { label: '个人作品', value: '0' },
      { label: '优秀站点', value: '1' },
      { label: '友情链接', value: '2' },
    ],
  },

  // 链接 - 优秀站点和友情链接显示
  {
    field: 'url',
    label: '链接',
    component: 'Input',
    placeholder: '请输入链接地址',
    showCondition: (formData) => formData.type === '1' || formData.type === '2',
    rules: [
      { required: true, message: '请输入链接地址', trigger: 'blur' },
      { type: 'url', message: '请输入正确的链接地址', trigger: 'blur' },
    ],
  },

  // ============ 个人作品类型专用字段 (type === '0') ============
  {
    field: 'githubUrl',
    label: 'GitHub链接',
    component: 'Input',
    placeholder: '请输入GitHub仓库地址（可选）',
    showCondition: (formData) => formData.type === '0',
    props: {
      clearable: true,
    },
    rules: [{ type: 'url', message: '请输入正确的链接地址', trigger: 'blur' }],
  },
  {
    field: 'giteeUrl',
    label: 'Gitee链接',
    component: 'Input',
    placeholder: '请输入Gitee仓库地址（可选）',
    showCondition: (formData) => formData.type === '0',
    props: {
      clearable: true,
    },
    rules: [{ type: 'url', message: '请输入正确的链接地址', trigger: 'blur' }],
  },
  {
    field: 'demoUrl',
    label: '在线演示链接',
    component: 'Input',
    placeholder: '请输入在线演示地址（可选）',
    showCondition: (formData) => formData.type === '0',
    props: {
      clearable: true,
    },
    rules: [{ type: 'url', message: '请输入正确的链接地址', trigger: 'blur' }],
  },
  {
    field: 'techStack',
    label: '技术栈',
    component: 'Input',
    showCondition: (formData) => formData.type === '0',
    render: (form) => {
      // 确保techStack是数组
      if (!Array.isArray(form.techStack)) {
        form.techStack =
          typeof form.techStack === 'string' && form.techStack
            ? form.techStack.split(',').filter(Boolean)
            : []
      }

      // 使用临时字段存储输入值
      if (!form._techStackInput) {
        form._techStackInput = ''
      }

      const handleInputConfirm = () => {
        const value = form._techStackInput.trim()
        if (value && !form.techStack.includes(value)) {
          form.techStack.push(value)
          form._techStackInput = ''
        }
      }

      const handleTagClose = (tag) => {
        const index = form.techStack.indexOf(tag)
        if (index > -1) {
          form.techStack.splice(index, 1)
        }
      }

      return h('div', { class: 'tech-stack-container' }, [
        // 输入框区域 - 放在最上面
        h('div', { class: 'tech-stack-input-wrapper' }, [
          h(ElInput, {
            modelValue: form._techStackInput,
            'onUpdate:modelValue': (val) => {
              form._techStackInput = val
            },
            placeholder: '输入技术栈名称，按回车添加',
            clearable: true,
            onKeyup: (e) => {
              if (e.key === 'Enter') {
                handleInputConfirm()
              }
            },
            onBlur: handleInputConfirm,
          }),
        ]),
        // 标签展示区域 - 放在输入框下方
        h('div', { class: 'tech-stack-tags-container' }, [
          form.techStack.length > 0
            ? h('div', { class: 'tech-stack-tags' }, [
                form.techStack.map((tag) =>
                  h(
                    ElTag,
                    {
                      key: tag,
                      closable: true,
                      type: 'primary',
                      effect: 'plain',
                      size: 'default',
                      onClose: () => handleTagClose(tag),
                    },
                    () => tag,
                  ),
                ),
              ])
            : h('div', { class: 'tech-stack-empty' }, '暂无技术栈，请在输入框中添加'),
        ]),
      ])
    },
  },
  {
    field: 'projectIntro',
    label: '项目介绍',
    component: 'Input',
    placeholder: '请输入项目介绍',
    showCondition: (formData) => formData.type === '0',
    props: {
      type: 'textarea',
      rows: 4,
      maxlength: 500,
      showWordLimit: true,
    },
    rules: [{ max: 500, message: '项目介绍不能超过500个字符', trigger: 'blur' }],
  },
  {
    field: 'coreFeatures',
    label: '核心功能',
    component: 'Input',
    placeholder: '请输入核心功能描述',
    showCondition: (formData) => formData.type === '0',
    props: {
      type: 'textarea',
      rows: 4,
      maxlength: 500,
      showWordLimit: true,
    },
    rules: [{ max: 500, message: '核心功能描述不能超过500个字符', trigger: 'blur' }],
  },

  // ============ 通用字段（排序、状态） ============
  {
    field: 'orderNum',
    label: '排序',
    component: 'Input',
    placeholder: '请输入排序号',
    props: {
      type: 'number',
      min: 0,
      class: 'number-input',
    },
    defaultValue: 5,
    rules: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  },
  {
    field: 'status',
    label: '状态',
    component: 'Radio',
    defaultValue: '1',
    options: [
      { label: '启用', value: '1' },
      { label: '禁用', value: '0' },
    ],
    rules: [{ required: true, message: '请选择状态', trigger: 'change' }],
  },
]

/**
 * 获取表单默认值
 */
export const getDefaultFormData = () => {
  return {
    id: '',
    type: '0', // 默认个人作品
    // 通用字段
    icon: '',
    title: '',
    description: '',
    url: '',
    // 个人作品字段
    coverImage: '',
    githubUrl: '',
    giteeUrl: '',
    demoUrl: '',
    techStack: [],
    projectIntro: '',
    coreFeatures: '',
    // 通用字段
    orderNum: 5,
    status: '1',
  }
}
